package com.yantong.controller.api;

import com.yantong.annotation.LoginUser;
import com.yantong.controller.BaseController;
import com.yantong.exception.BDException;
import com.yantong.mapper.YfzWithdrawalsMapper;
import com.yantong.pay.yfz.domain.pay.domain.withdraw.CustomerAccountQueryResp;
import com.yantong.pay.yfz.domain.pay.domain.withdraw.Withdraw4SubMerchantResponse;
import com.yantong.pay.yfz.pay.YFZPayutil;
import com.yantong.pojo.Centre;
import com.yantong.pojo.Member;
import com.yantong.pojo.YfzWithdrawals;
import com.yantong.result.ResultVo;
import com.yantong.service.CentreService;
import com.yantong.service.MemberService;
import com.yantong.utils.PageUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import springfox.documentation.annotations.ApiIgnore;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: juzi
 * @date: 2021/10/25
 * @time: 16:12
 */
@ApiIgnore
@Controller
@RequestMapping("/wxapi/memberYfz")
public class ApiMemberYfzController extends BaseController {

    @Autowired
    private CentreService centreService;
    @Autowired
    private YfzWithdrawalsMapper yfzWithdrawalsMapper;
    @Autowired
    private MemberService memberService;

    /**
     * 分账商户提现
     */
    @RequestMapping("/withdrawalForSubMerchant")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public ResultVo memberYfzWithdrawalForSubMerchant(@ApiIgnore @LoginUser Member member, BigDecimal payAmount) throws Exception {
        Centre centre = centreService.getCentreById(member.getCentreId());
        String sn = RandomStringUtils.randomAlphanumeric(10);
        String outTradeNo = "YFZ_TX_".concat(sn);
        String remark = "分账商户提现";
        String notifyUrl = "";
        if (BigDecimal.valueOf(1).compareTo(payAmount) >= 0) {
            throw new BDException("单次提现金额必须大于1元");
        }
        //先判断余额是否充足
        if (member.getSettlementMoney().compareTo(payAmount) >= 0) {
            //member.getYplCustomerCode()已被删除 , 暂时注释掉
//            CustomerAccountQueryResp response = YFZPayutil.accountQuery(centre, member.getYplCustomerCode());
            CustomerAccountQueryResp response = YFZPayutil.accountQuery(centre, null);
            if (!"0000".equals(response.getReturnCode())) {
                throw new BDException(response.getReturnMsg());
            } else {
                if (BigDecimal.valueOf(response.getAvailableBalance()).divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_DOWN).compareTo(payAmount) < 0) {
                    throw new BDException("可提现余额不足！");
                }
            }
        } else {
            throw new BDException("可提现余额不足！");
        }
//        Withdraw4SubMerchantResponse response = YFZPayutil.WithdrawalForSubMerchant(centre, notifyUrl, member.getYplCustomerCode(), remark, outTradeNo, payAmount);
        Withdraw4SubMerchantResponse response = YFZPayutil.WithdrawalForSubMerchant(centre, notifyUrl, null, remark, outTradeNo, payAmount);
        YfzWithdrawals yfzWithdrawals = new YfzWithdrawals();
        yfzWithdrawals.setApplyno(sn);
        yfzWithdrawals.setMid(member.getId());
        yfzWithdrawals.setRealname(member.getMerchantName());
        yfzWithdrawals.setMobile(member.getContactPhone());
        yfzWithdrawals.setMoney(payAmount);
//        yfzWithdrawals.setContent("分账商户提现，商户号：" + member.getYplCustomerCode());
        yfzWithdrawals.setContent("分账商户提现，商户号：");
        yfzWithdrawals.setCentreId(member.getCentreId());
        yfzWithdrawals.setBankcard(member.getSettleAccountNo());
        yfzWithdrawals.setIdcard(member.getLawyerCertNo());
        yfzWithdrawals.setBankname(member.getOpenBank());
        yfzWithdrawals.setReturnCode(response.getReturnCode());
        yfzWithdrawals.setReturnMsg(response.getReturnMsg());
        yfzWithdrawals.setCreateTime(new Date());


        if (!"0000".equals(response.getReturnCode())) {
            yfzWithdrawals.setStatus(4);
        } else {
            yfzWithdrawals.setApplyTime(new Date());
            yfzWithdrawals.setTransactionNo(response.getTransactionNo());
            yfzWithdrawals.setStatus(3);
            yfzWithdrawals.setDaMoney(BigDecimal.valueOf(response.getActualFee()).divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_DOWN));
            yfzWithdrawals.setCommissionMoney(BigDecimal.valueOf(response.getProcedureFee()).divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_DOWN));
            //减扣余额
            Member member1 = new Member();
            member1.setId(member.getId());
            member1.setSettlementMoney(member.getSettlementMoney().subtract(payAmount));
            memberService.updateMember(member1);
        }
        yfzWithdrawalsMapper.insertSelective(yfzWithdrawals);
        return ResultVo.ok().put("data", response);
    }

    /**
     * 分账商户提现历史
     */
    @RequestMapping("/withdrawalForSubMerchant/logs")
    @ResponseBody
    public ResultVo memberYfzWithdrawalForSubMerchantLogs(@LoginUser Member member, int offset, int limit) {
        Map<String, Object> params = new HashMap<>();
        params.put("teamId", member.getId());
        int total = yfzWithdrawalsMapper.totalByParams(params);
        PageUtils<YfzWithdrawals> pageUtils = new PageUtils<>();
        pageUtils.setTotal(total);
        pageUtils.setRows(null);
        if (total > 0) {
            pageUtils.setRows(yfzWithdrawalsMapper.listByParams(params, new RowBounds(offset, limit)));
        }
        return ResultVo.ok().put("data", pageUtils);
    }
}
